package com.yonyou.cn.mongodbtest;

import com.mongodb.*;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.reactivestreams.client.MongoClients;
import com.yonyou.cn.mongodbtest.utils.MongoDBUtils;
import org.apache.commons.collections4.collection.SynchronizedCollection;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class TestMain {

    static AtomicLong counter = new AtomicLong(0);

    public static String dbname="czsb";

    public static int port=28017;
    public static String username="testUser";
    public static String password="testPass";
    //public static String table="SSSFM_SR_DETAIL_1300_1101_2019_1";
    //public static List<String> ips= Arrays.asList(new String[]{"192.168.50.123","192.168.50.124","192.168.50.125"});
    public static List<String> ips= Arrays.asList(new String[]{"10.10.65.6"});
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 15, 200, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(5));
   /* public static void aaaa(){
        MongoClientURI connectionString = new MongoClientURI("mongodb://:****@s-m5e80a9241323604.mongodb.rds.aliyuncs.com:3717,s-m5e053215007f404.mongodb.rds.aliyuncs.com:3717/admin"); // ****替换为root密码
        MongoClient client = new MongoClient(connectionString);
        MongoDatabase database = client.getDatabase("mydb");
        MongoCollection collection = database.getCollection("mycoll");
    }*/
  /* public static void asyn(){
//       MongoCredential credential = MongoCredential.createCredential(username, dbname, password.toCharArray());
//       MongoClientSettings setting =  MongoClientSettings.builder();
//       MongoClient mongoClient = MongoClients.create("mongodb://10.10.65.6:28017");
//       MongoDatabase database = mongoClient.getDatabase("czsb");

       //服务器实例表
       List servers = new ArrayList();
       servers.add(new ServerAddress("localhost", 28017));

        //配置构建器
       MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder();

        //传入服务器实例
       settingsBuilder.applyToClusterSettings(
               builder -> builder.hosts(servers));

        //构建 Client 实例
       MongoClient mongoClient = MongoClients.create(settingsBuilder.build());



   }*/
    /*public static void main(String[] args) {
        long stno = System.currentTimeMillis();
//        String table=args[0];
//        String num =args[1];
        String table="test09";
        String num ="600000";
        Integer threadNum=1;
        Long total = Long.parseLong(num);
        Long threadTotal=total/threadNum;
        MongoCollection<Document>  dbConnection = MongoDBUtils.getDBConnection(dbname, table, ips, port, username, password);
        Long startNum = 1L;
        for(int j=1;j<=threadNum;j++){
            executor.execute(new TestMain().new AddThread(j,startNum,startNum+threadTotal,dbConnection));
            startNum +=threadTotal;
        }
        while (true) {
            if (executor.isTerminated()){
                break;
            }

        }
        executor.shutdown();
        long enno = System.currentTimeMillis();
        System.out.println(table+"  over了---------------taskNum=run用时："+(enno-stno)/1000+"s");


    }*/
    public class AddThread implements Runnable {
        private final int taskNum;
        private final long startNum;
        private final long endNum;
        MongoCollection<Document>  dbConnection;
        public AddThread(int taskNum, long startNum, long endNum,MongoCollection<Document>  dbConnection) {
            this.taskNum = taskNum;
            this.startNum = startNum;
            this.endNum = endNum;
            this.dbConnection=dbConnection;
        }
        @Override
        public void run() {
//            synchronized (LockTest.class){
                long stno = System.currentTimeMillis();
                System.out.println();
                System.out.println("taskNum="+taskNum+" startNum ="+startNum+" endNum="+endNum);
                //Long addnum=taskNum*10000000L;
                Long j=(endNum-startNum)/100000L;
                System.out.println();
                for(int i=0;i<j;i++){
                    Long addnumtmp = startNum+i*100000L;
                    System.out.println("["+addnumtmp+","+(addnumtmp+100000)+")");
                    add(addnumtmp,dbConnection);
                }
                long enno = System.currentTimeMillis();
                System.out.println("我叫郭德纲----------------taskNum="+taskNum+"run用时："+(enno-stno)/1000+"s");
//            }


        }
        public void add(Long addnumtmp,MongoCollection<Document>  dbConnection){
            List<Document> list = new ArrayList<>();
            List<String> ids= new ArrayList<>();
            for (Long i = addnumtmp; i < addnumtmp+100000; i++) {
                String id = UUID.randomUUID().toString().replace("-", "");
                ids.add(id);
                int month = (int) (Math.random() * 12 + 1);
                int age = (int) (Math.random() * 100 + 1);
                Document document = new Document("name", "user" + i).append("month",month+"")
                        //.append("_id", i)
                        .append("_id", id)
                        .append("age", i/100).
                                append("sort",counter.incrementAndGet()).
                                append("a", "aaaaaaaaaaaa").
                                append("b", "bbbbbbbbbbbbb").
                                append("ccc", "cccccccccccccc").
                                append("d", "的萨芬大师傅犯得上犯得上").
                                append("aw", "dfdsfdsfdsfdsds").
                                append("v", "bbbbbbbbbbb").
                                append("w", "aaaaaaaaaaaa").
                                append("y", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa").
                                append("iiii", "qewqeqewqewqewqewqeqeqeq").
                                append("iiiiii", "sdfsfdssfdsgffdgfdgd").
                                append("ooooooo", "hgkjjhkj").
                                append("oooo", "retetrret").
                                append("ppppp", "hggfhgfhfhgf").
                                append("jjjjjj", "yutuyytuytu").
                                append("qqqqqq", "oiuoiuouoiuoiuo").
                                append("tttttt", "oiuiuoiuoiuoiuouiooi").
                                append("iiiiii", "oiuuio").
                                append("kkkkkkk", "aaaaaaaaaaaa").
                                append("lllllll", "aaaaaaaaaaaa").
                                append("iiiiii", "aaaaaaaaaaaa").
                                append("iiiiiiiii", "aaaaaaaaaaaa").
                                append("lllllllllllllll", "aaaaaaaaaaaa").
                                append("xzcfxzcxzcxzc", "aaaaaaaaaaaa").
                                append("fdsfdsfdsfdsfdsf", "aaaaaaaaaaaa").
                                append("sdfdsfdsfdsfdsfds", "aaaaaaaaaaaa").
                                append("sdfdsfdsfdsfdsfsfdsfdsfdsf", "aaaaaaaaaaaa").
                                append("wwwwww", "aaaaaaaaaaaa").
                                append("rrrrrrrr", "aaaaaaaaaaaa").
                                append("mnjhkjh", "aaaaaaaaaaaa").
                                append("werewrewrewrw", "aaaaaaaaaaaa").
                                append("qwerty", "aaaaaaaaaaaa").
                                append("lkjh", "aaaaaaaaaaaa").
                                append("mnb", "aaaaaaaaaaaa").
                                append("fghj", "aaaaaaaaaaaa").
                                append("tw", "aaaaaaaaaaaa").
                                append("ewrwrwrw", "aaaaaaaaaaaa");

                list.add(document);
            }
            //排序


            long delbegin = System.currentTimeMillis();
            BasicDBObject query= new BasicDBObject();
            BasicDBList values = new BasicDBList();
            values.addAll(ids);
            query.put("_id", new BasicDBObject("$in", values));
            dbConnection.deleteMany(query);
            long delend = System.currentTimeMillis();
            System.out.println("删除"+(delend-delbegin)/1000+"秒");

            long begin = System.currentTimeMillis();
            InsertManyOptions order=new InsertManyOptions();
            order.ordered(false);
            dbConnection.insertMany(list,order);
            long end = System.currentTimeMillis();
            System.out.println("新增"+(end-begin)/1000+"秒");
        }

    }
}


